import React from 'react';
import { Router, Route, Switch, Redirect } from 'react-router-dom';
import 'antd/dist/antd.min.css';
import Layout from './pages/Layout';
import Login from './pages/Login';
import Test from './pages/Test';
import { hasToken } from 'utils/storage';
import history from 'utils/history';

export default function App() {
  return (
    <Router history={history}>
      {/* 定义一个函数
      <TestRenderProps
        render={(list) => list.map((item) => <h1 key={item}>{item}</h1>)}
      />
      <TestRenderProps
        render={(list) => list.map((item) => <i key={item}>{item}</i>)}
      /> */}
      <Switch>
        <Route path="/login" component={Login}></Route>
        <Route path="/test" component={Test}></Route>
        {/* 匹配到其他路径都进入到layout */}
        {/* 如果要进入到layout页面，需要判断是否由token */}
        {/* <Route
          path="/"
          // component={Layout}
          render={(props) => {
            if (hasToken()) {
              console.log(1);
              // 如果有token 跳转到layout页面
              return <Layout {...props} />;
            }
            return <Redirect to="/login"></Redirect>;
          }}
        ></Route> */}
        {/* 2、直接调用组件 */}
        <AutoRoute path="/" component={Layout}></AutoRoute>
      </Switch>
    </Router>
  );
}

class AutoRoute extends React.Component {
  render() {
    // 2、为了能够复用，需要通过父传子传参
    const { path, component: Component, ...restProps } = this.props;
    return (
      <div>
        {/* 1、将route迁移到组件内 */}
        <Route
          {...restProps}
          path={path}
          render={(props) => {
            if (hasToken()) {
              // 组件需要大写，重命名
              return <Component {...props} />;
            }
            return <Redirect to="/login"></Redirect>;
          }}
        ></Route>
      </div>
    );
  }
}

// class TestRenderProps extends React.Component {
//   state = {
//     list: [1, 2, 3],
//   };
//   render() {
//     const { list } = this.state;
//     // 父传子通过this.props接收
//     // 接收会调用,并传值
//     const { render } = this.props;
//     return <div>{render(list)}</div>;
//   }
// }
